<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.input.type" style="width: 120px">
            <el-option label="文件单号" value="contract_no"></el-option>
            <el-option label="来源单号" value="source_no"></el-option>
          </el-select>
          <VBatchInput
            v-model="form.input.value"
            @search="query"
            class="w-60"
          />
        </VGroup>
        <VSelect
          v-model="form.supplier_name"
          placeholder="供应商"
          type="supplierName"
          allow-create
          style="min-width: 200px"
          multiple
          collapse-tags
          clearable
          filterable
        />
        <VCascader
          v-model="form.purchase_user_id"
          placeholder="采购人员"
          multiple
          collapse-tags
          style="min-width: 160px"
        />
        <VSelect
          v-model="form.doc_type"
          placeholder="文件类型"
          :options="options.doc_type"
          multiple
          collapse-tags
          style="min-width: 160px"
        />
        <VSelect
          v-model="form.company_id"
          placeholder="公司主体"
          :options="options.company_id"
          multiple
          collapse-tags
          style="min-width: 160px"
        />
        <VSelect
          v-model="form.enable"
          placeholder="是否作废"
          :options="options.enable"
          multiple
          collapse-tags
          style="min-width: 160px"
        />
        <VSelect
          v-model="form.send_status"
          placeholder="发送状态"
          :options="options.send_status"
          multiple
          collapse-tags
          style="min-width: 160px"
        />
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 100px">
            <el-option label="生成时间" value="create_time"></el-option>
            <el-option label="入库时间" value="inbound_time"></el-option>
          </el-select>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VButton
          auth="/purchase/finance/verification/file/download"
          type="primary"
          :loading="loading"
          @click="handleBatch('download')"
        >批量下载</VButton
        >
        <VButton
          auth="/purchase/finance/verification/file/send"
          type="primary"
          :loading="loading"
          @click="handleBatch('send')"
        >批量发送</VButton
        >
        <VButton
          auth="/purchase/finance/verification/file/cancel"
          type="primary"
          :loading="loading"
          @click="handleBatch('cancel')"
        >批量作废</VButton
        >
        <VExport
          auth="/purchase/finance/verification/file/export"
          mainKey="c_id"
          :name="baseName"
          :tableRef="tableRef"
          class="ml-auto"
        />
      </template>
      <template #operation="{ row, rowIndex }">
        <div class="flex items-center">
          <VButton
            auth="/purchase/finance/verification/file/look"
            link
            type="primary"
            v-if="[3, 4, 5, 6].includes(row.doc_type) && row?.enable == 2"
            @click="handleRow('look', row)"
          >预览</VButton
          >
          <el-dropdown
            v-if="row?.enable == 2"
            trigger="click"
            @command="(name) => handleRow(name, row, rowIndex)"
          >
            <el-button link type="primary">
              操作<i class="dk-iconfont icon-ArrowDown" />
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  command="download"
                  v-if="$auth('/purchase/finance/verification/file/download')&&!([4,6].includes(row.doc_type))"
                >下载PDF文件</el-dropdown-item
                >
                <el-dropdown-item
                  command="download1"
                  v-if="$auth('/purchase/finance/verification/file/download')"
                >下载EXCEL文件</el-dropdown-item
                >

                <el-dropdown-item
                  command="send1"
                  v-if="$auth('/purchase/finance/verification/file/send')&&!([4,6].includes(row.doc_type))"
                >发送PDF文件</el-dropdown-item
                >
                <el-dropdown-item
                  command="send"
                  v-if="$auth('/purchase/finance/verification/file/send')"
                >发送EXCEL文件</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <VButton
            auth="/purchase/finance/verification/file/log"
            link
            type="primary"
            @click="handleRow('log', row)"
          >日志</VButton
          >
        </div>
      </template>
    </VTable>
    <VLog ref="logRef" />
    <Pdf ref="pdfRef" @success="query" />
    <SendDownload ref="sendDownloadRef" @success="query" />
  </VPage>
</template>
<script setup lang="jsx">
  import { ElMessage } from "element-plus";
  import { $auth } from "@/utils";
  import {
    billFileList,
    billFileBatchDownload,
    billFileBatchCancel,
    billFileDownload,
  } from "./api.js";
  import { getOption } from "@/api/public";
  import { resMessage } from "@/utils/res";
  import Pdf from "@/views/settings/contract/components/Contract/PdfTitle";
  import SendDownload from "./components/sendDownload";
  const baseName = "billing_file";
  const tableRef = ref();

  // 查询
  const query = () => {
    tableRef?.value.query();
  };
  // 获取options
  const options = ref({});
  Promise.all([
    getOption({ type: baseName }).then((res) => res.data),
    Promise.resolve({ test: [{ label: "没有数据", value: 1 }] }),
  ]).then((res) => {
    options.value = res.reduce(
      (acc, cur) => ((acc = { ...acc, ...cur }), acc),
      {}
    );
  });
  const loading = ref(false);
  const sendDownloadRef = ref();
  const handleBatch = (name) => {
    const selection = tableRef.value.$table.getCheckboxRecords();
    let nameArr = ["download", "send"];
    if (!nameArr.includes(name) && !selection.length) {
      ElMessage.warning("请先选择行");
      return;
    }
    const c_ids = selection.map((d) => d.c_id);
    const handleOpenContract = (is_send) => {
      const form = tableRef.value.getQueryForm();
      if (!c_ids?.length && !Object.keys(form).length) {
        return ElMessage.warning("请先筛选数据后重试!");
      }
      sendDownloadRef?.value.open({ c_ids, ...form, is_send });
    };
    const handle = {
      download: () => {
        handleOpenContract(1);
      },
      send: () => {
        handleOpenContract(2);
      },
      cancel: () => {
        loading.value = true;
        billFileBatchCancel({ c_ids })
          .then((res) => {
            resMessage({
              res,
              success: () => {
                ElMessage.success("操作成功");
                query();
              },
            });
          })
          .finally(() => {
            loading.value = false;
          });
      },
    };
    handle[name]();
  };
  const logRef = ref();
  const pdfRef = ref();
  // 单行操作
  const handleRow = (name, row, rowIndex) => {
    const { c_id, doc_type } = row;
    const handle = {
      download: () => {
        let field = [
          "template_name",
          "supplier_name",
          "company_name",
          "purchase_user_name",
          "month",
        ];
        // if (doc_type != 4) {
        pdfRef?.value.pdf(
          row,
          {
            isLook: true,
          },
          field
        );
      },
      look: () => {
        let field = [
          "template_name",
          "supplier_name",
          "company_name",
          "purchase_user_name",
          "month",
        ];
        pdfRef?.value.view(
          row,
          {
            isLook: true,
          },
          field
        );
      },
      download1: () => {
        loading.value = true;
        billFileBatchDownload({
          c_ids: [c_id],
          is_send: 1,
        })
          .then((res) => {
            resMessage({
              res,
              success: () => {
                ElMessage.success("操作成功,文件下载完成后会发送到飞书账户！");
                query();
              },
            });
          })
          .finally(() => {
            loading.value = false;
          });
      },
      send: () => {
        loading.value = true;
        billFileBatchDownload({ c_ids: [c_id], is_send: 2 })
          .then((res) => {
            resMessage({
              res,
              success: () => {
                ElMessage.success(
                  "操作成功,系统处理完成后会以邮件的形式发送到您的邮箱，请注意查收！"
                );
                query();
              },
            });
          })
          .finally(() => {
            loading.value = false;
          });
      },
      send1: () => {
        loading.value = true;
        billFileBatchDownload({
          c_ids: [c_id],
          is_send: 2,
          billing_contract_type: 2,
          deliver_list_type: 2,
          billing_list_type: 2,
          billing_detail_type: 2,
        })
          .then((res) => {
            resMessage({
              res,
              success: () => {
                ElMessage.success(
                  "操作成功,系统处理完成后会以邮件的形式发送到您的邮箱，请注意查收！"
                );
                query();
              },
            });
          })
          .finally(() => {
            loading.value = false;
          });
      },
      log: () => {
        logRef?.value.open({ log_type: baseName, c_id });
      },
    };
    handle[name]();
  };
  // 列表配置
  const tableOptions = reactive({
    showHeaderOverflow: false,
    formConfig: {
      data: {
        input: { type: "contract_no", value: "" },
        dateRange: { type: "create_time", value: [], range: true },
        enable:[2]
      },
    },
    columns: [
      { type: "checkbox", width: 40, fixed: "left" },
      {
        title: "文件单号",
        field: "contract_no",
        minWidth: 180,
        slots: {
          default: ({ row }) => {
            if ([3, 4, 5, 6].includes(row.doc_type)) {
              return (
                <el-link type="primary" onClick={() => handleRow("look", row)}>
                  {row.contract_no}
                </el-link>
              );
            } else {
              return <div>{row.contract_no}</div>;
            }
          },
        },
      },
      { title: "文件类型", field: "doc_type_name", minWidth: 120 },
      {
        title: "来源单号",
        minWidth: 160,
        slots: {
          default: ({ row }) => (
            <div>
              <VText value={row?.source_no?.join(",") || "-"}></VText>
            </div>
          ),
        },
      },
      { title: "采购人员", field: "purchase_user_name", minWidth: 160 },
      {
        minWidth: 260,
        title: "供应商信息",
        slots: {
          default: ({ row }) => (
            <div>
              <VText title="供应商名称" value={row.supplier_name}></VText>
              <VText title="供应商id">{row.supplier_code}</VText>
            </div>
          ),
        },
      },
      { title: "公司主体", field: "company_name", minWidth: 220 },
      {
        title: "入库月份",
        field: "month",
        minWidth: 160,
        slots: {
          default: ({ row }) => (
            <div>
              <VText value={row?.month?.join(",") || "-"}></VText>
            </div>
          ),
        },
      },
      {
        title: "生成时间",
        field: "create_time",
        minWidth: 160,
      },
      { title: "是否作废", field: "enable_name", minWidth: 80 },
      { title: "发送状态", field: "send_status_name", minWidth: 80 },
      { title: "收件人邮箱", field: "send_user", minWidth: 160 },
      { title: "下载次数", field: "download_count", minWidth: 80 },
      {
        title: "操作",
        fixed: "right",
        width: 200,
        slots: { default: "operation" },
      },
    ],
    proxyConfig: {
      autoLoad: false,
      ajax: {
        query: ({ page, form }) => billFileList({ ...form, ...page }),
      },
    },
  });
</script>
<style lang="scss" scoped></style>
